import express from "express";
import {
  encryptObject,
  generateOtp,
  generateRandomString,
  sendOTP,
} from "../../utils";
import { type emailType, emailTypeList } from "../../common";
import { delUser, setUser, setUserCount, verifyOtp } from "../../Db/redis";
import { addUser, findUser } from "../../Db/db";
import { sessionValidator, getIp } from "../../nextFunction";
export const userRouter = express.Router();
// userRouter.use(
//   session({
//     secret: "yanmengs",
//     // name: "StoreIt",
//     resave: false,
//     saveUninitialized: true,
//     cookie: {
//       maxAge: 1000 * 3600 * 24, // 1天
//       secure: false, // 生产环境应设为 true (HTTPS)
//       httpOnly: true,
//       sameSite: "none",
//     },
//   } as any)
// );
let cookieOption = {
  httpOnly: true,
  secure: true,
  maxAge: 24 * 60 * 60 * 1000,
  sameSite: "none",
};
//获取验证码
userRouter.post("/getLogiOtp", getIp, (req: any, res) => {
  const { type, email } = req.body;
  const { userIp } = req;
  if (!type || !email) {
    console.log(userIp + type + email + "参数缺失");
    res.status(500).json({
      code: 500,
      message: "参数丢失",
    });
  } else if (emailTypeList.indexOf(type as string) === -1) {
    console.log(userIp + type + email + "参数错误");
    res.status(500).json({
      code: 500,
      message: "参数错误",
    });
  } else {
    sendOTP(email as string, type as emailType, userIp as string)
      .then((r) => {
        res.status(200).json({
          code: 200,
          message: "发送成功",
        });
      })
      .catch((e) => {
        res.status(200).json({
          code: 500,
          message: e,
        });
      });
  }
});
//登陆
userRouter.post("/login", getIp, async (req: any, res: any) => {
  const { otp, email } = req.body;
  const { userIp } = req;
  const sessionId = "";
  sessionId && delUser(sessionId);
  // 如果缺少参数，提前返回
  if (!otp || !email) {
    console.log(userIp + otp + email + "参数缺失");
    return res.status(200).json({
      code: 500,
      message: "参数丢失",
    });
  }

  const r = await verifyOtp(email, otp, "login");
  if (!r) {
    console.log(userIp + otp + email + "验证码或邮箱错误");
    return res.status(200).json({
      code: 500,
      message: "验证码或邮箱错误",
    });
  }
  if (r) {
    try {
      const user = await findUser(email);
      if (user && user["_id"]) {
        // const sessionId = generateRandomString();
        // await delUser(sessionId);
        // await setUser(email, user["_id"], sessionId);
        let data = { email: email, accountId: user["_id"] };
        console.log(userIp + otp + email + "登陆成功");
        const token = encryptObject(data);
        res.cookie("storeIt", token, cookieOption);
        return res.status(200).json({
          code: 200,
          message: "登陆成功",
          token: "storeIt=" + token,
        });
      } else {
        console.log(userIp + otp + email + "暂无此用户");
        return res.status(200).json({
          code: 500,
          message: "暂无此用户",
        });
      }
    } catch (err) {
      console.log(userIp + otp + email + "服务器错误" + err);
      return res.status(200).json({
        code: 500,
        message: "服务器错误",
      });
    }
  }
});
// 注册
userRouter.post("/register", getIp, async (req: any, res: any) => {
  const { otp, email, name } = req.body;
  const { userIp } = req;

  if (!otp || !email || !name) {
    console.log(userIp + otp + email + "参数缺失");
    return res.status(400).json({
      code: 400,
      message: "参数丢失",
    });
  }

  // 验证验证码
  const r = verifyOtp(email, otp, "register");
  if (r) {
    try {
      if (await findUser(email)) {
        console.log(await findUser(email));
        console.log(userIp + otp + email + "用户已存在");
        return res.status(200).json({
          code: 500,
          message: "用户已存在",
        });
      }
      // 调用异步函数添加用户
      const { _id } = await addUser({
        email,
        fullName: name,
        avatar:
          "https://dthezntil550i.cloudfront.net/p4/latest/p42102052243097410008650553/1280_960/12bc8bc0-2186-48fb-b432-6c011a559ec0.png",
        accountId: new Date().getTime().toString() + generateOtp(),
      });

      setUserCount(_id.toString(), 0);

      console.log(userIp + otp + email + "注册成功");
      let data = { email, accountId: _id.toString() };
      const token = encryptObject(data);
      res.cookie("storeIt", token, cookieOption);
      res.status(200).json({
        code: 200,
        message: "注册成功！",
        token: "storeIt=" + token,
      });
    } catch (err) {
      console.log(userIp + otp + email + "注册成功" + err);
      // 捕获添加用户时的错误
      res.status(200).json({
        code: 500,
        message: `注册失败: ${err.message}`, // 将错误信息返回给客户端
      });
    }
  } else {
    res.status(400).json({
      code: 400,
      message: "验证码或邮箱错误",
    });
  }
});

//获取用户信息
userRouter.get("/userInfo", getIp, sessionValidator, async (req: any, res) => {
  const { email, accountId } = req;
  console.log(email, accountId, "userInfo");
  const { userIp } = req;
  const user = await findUser(email as string, accountId as string);
  if (user && user["_id"]) {
    console.log(
      userIp + email + "---" + accountId + "---" + "获取用户信息成功"
    );
    res.status(200).json({
      code: 200,
      data: user,
    });
  } else {
    console.log(userIp + "获取用户信息失败");
    res.status(200).json({
      code: 500,
      message: "暂无此用户",
    });
  }
});

//退出登录
userRouter.post(
  "/logout",
  getIp,
  sessionValidator,
  async (req: any, res: any) => {
    const { userIp } = req;
    res.cookie("storeIt", "", cookieOption);
    res.status(200).json({
      code: 200,
      message: "退出成功",
    });
  }
);
